<?php
namespace backend\controllers;
use backend\models\Tags;
use backend\models\Links;
use yii\web\Controller;
use Yii;
use yii\base\Exception;


class TagsController extends Controller{

    public function actionAdd(){
        $model = new Tags();
        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if($model->load($data) && $model->validate()){
                $model->create_time = time();
                if($model->save()){
                    Yii::$app->session->setFlash('info', $model->tagname .'标签已添加成功');
                }
            }
        }
        return $this->render('tag_add', ['model' => $model]);
    }

    public function actionList(){
        $data = Tags::find()->asArray()->all();
        return $this->render('tag_list',[ 'tagdata' => $data]);
    }

    public function actionDel(){
        try{
            $tagid = Yii::$app->request->get('tagid');
            if(empty($tagid)){
                throw new \Exception('参数有误');
            }

            $data = Links::find()->where('tagid = :id', [':id' => $tagid])->one();
            if($data){
                throw new \Exception('该标签已经被使用，禁止删除！');
            }
            if(!Tags::deleteAll('tagid = :id', [':id' => $tagid])){
                Yii::$app->session->setFlash('info', '删除失败');
            }
        }catch (Exception $e){
            Yii::$app->session->setFlash('info', $e->getMessage());
        }
        return $this->redirect(['list']);
    }
}
